const contentSymbionts = require("content-symbiont");
const data = require("self").data;
const DAO = require("cnl-dao").CNL_DAO;
const simpleStorage = require("simple-storage");
const pageMod = require("page-mod");
//Note: I change tab-browser.js, add the following line:
//this.__defineGetter__("ownerBrowser", function() browser);
//in tabConstructor, bellow the line:
//let browser = win.gBrowser.getBrowserForTab(element);
exports.main = function(options, callbacks) {
    pageMod.add(new pageMod.PageMod({
        include: "*",
        onReady: function(wrappedWindow) {
            let idx = matchSrcIndex(wrappedWindow.location.toString());
            if(idx == -1){
                let sources = simpleStorage.storage.sources;
                if (sources == null) {
                    simpleStorage.storage.selectedSource = 0;//index in sources
                    sources = simpleStorage.storage.sources = DEFAULT_SOURCES;
                }
                let jsData = {
                    HANDLE_ICON_URL: data.url("resize.png"),
                    BACKGROUND_URL: data.url("background.png"),
                    CNL_HTML: data.load("cnl.html"),
                    sources: sources,
                    srcIdx: simpleStorage.storage.selectedSource,
                    arrowURL: data.url("drop_down.png")
                };
                modPage(wrappedWindow,
                        ["jquery-1.4.2.min.js", "jquery.metadata.js", "cnl.js", "jquery.ui.core.js", "jquery.ui.widget.js",
                            "ui.combobox.js", "resizer.js", "cnl-selection.js", "cnl-search.js"],
                        ["cnl.css", "ui.combobox.css"],
                        jsData,
                        allPageJsFunc);
            }
            else{
                modPage(wrappedWindow,
                        ["jquery-1.4.2.min.js", "cnl-frame.js", "cnl-selection.js", "filter.js"],
                        [],
                        DEFAULT_SOURCES[idx],
                        cnlFrameJsFunc);
            }
            //
            function cnlFrameJsFunc(msg, cb){
                switch (msg.method) {
                    case "log":
                        console.log("onMessage from CNL frame", msg.arg);
                        break;
                    case "doQuery":
                        console.log("onMessage from CNL frame", msg.arg.query);
                        wrappedWindow.top.wrappedJSObject.CnlSearch.doQuery(msg.arg.query, msg.arg.srcIdx, msg.arg.remind);
                        break;
                }
            }
        }
    }));
};
function allPageJsFunc(msg, cb){
    switch (msg.method) {
        case "log":
            console.log("onMessage", msg.arg);
            break;
        case "getRemindData":
            let remindData = DAO.getWordData(msg.arg);
            cb(remindData);
            break;
    }
}
function modPage(wrappedWindow, scriptUrls, cssUrls, jsData, jsFunc){
    wrappedWindow.wrappedJSObject.CNL = {data: jsData, sendMessage: jsFunc};
    let heads = wrappedWindow.document.getElementsByTagName("head");
    let node = heads.length > 0 ? heads[0] : wrappedWindow.document.body;
    let i, script, link;
    for (i = 0; i < scriptUrls.length; i++) {
        script = wrappedWindow.document.createElement("script");
        script.language = "JavaScript";
        script.type = "text/javascript";
        script.src = data.url(scriptUrls[i]);
        node.appendChild(script);
    }
    for (i = 0; i < cssUrls.length; i++) {
        link = wrappedWindow.document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
		link.href = data.url(cssUrls[i]);
        node.appendChild(link);
    }
}
///////////////
const DEFAULT_SOURCES = [
//    {name, url, target, scrollX, scrollY, omitEncoding}
    {   name: 'tratu.vn/English-Vi\u1EC7t',
        url: 'http://tratu.vn/dispatchaddon.php?dict=en_vn&title=*'
    },
    {   name: 'tratu.vn/English-English',
        url: 'http://tratu.vn/dispatchaddon.php?dict=en_en&title=*'
    },
    {   name: 'tratu.vn/Vi\u1EC7t-English',
        url: 'http://tratu.vn/dispatchaddon.php?dict=vn_en&title=*'
    },
    {   name: 'tratu.vn/Fran\u00E7ais-Vi\u1EC7t',
        url: 'http://tratu.vn/dispatchaddon.php?dict=fr_vn&title=*'
    },
    {   name: 'tratu.vn/Vi\u1EC7t-Fran\u00E7ais',
        url: 'http://tratu.vn/dispatchaddon.php?dict=vn_fr&title=*'
    },
    {   name: 'tratu.vn/Vi\u1EC7t-Vi\u1EC7t',
        url: 'http://tratu.vn/dispatchaddon.php?dict=vn_vn&title=*'
    },
    {   name: 'tratu.vn/\u65E5\u672C\u8A9E-Vi\u1EC7t',
        url: 'http://tratu.vn/dispatchaddon.php?dict=jp_vn&title=*'
    },
    {   name: 'tratu.vn/Vi\u1EC7t-\u65E5\u672C\u8A9E',
        url: 'http://tratu.vn/dispatchaddon.php?dict=vn_jp&title=*'
    },
    {   name: 'tratu.vn/English-\u65E5\u672C\u8A9E',
        url: 'http://tratu.vn/dispatchaddon.php?dict=en_jp&title=*'
    },
    {   name: 'tratu.vn/\u65E5\u672C\u8A9E-English',
        url: 'http://tratu.vn/dispatchaddon.php?dict=jp_en&title=*'
    },
    {   name: 'tratu.vn/Vi\u1EBFt T\u1EAFt',
        url: 'http://tratu.vn/dispatchaddon.php?dict=td_vt&title=*'
    },
    {   name: 'Oxford Advanced Learner\'s',
        url: 'http://www.oup.com/oald-bin/web_getald7index1a.pl?sourceid=Open-Search&search_word=*',
        target: 'entryContent'
    },
    {   name: 'vdict.com',
        url: 'http://vdict.com/fsearch.php?dictionaries=eng2vie_vie2eng_foldoc&word=*'
    },
    /*{   name: 'edictx.com',
        url: 'http://edictx.com/edictx/?dict=1&mode=addon&word=*'
    },
    {   name: 'tudientiengviet.net/English-Vi\u1EC7t',
        url: 'http://www.tudientiengviet.net/get.php?mode=quickdict&dict=en-vi&word=*',
        target: 'entryContent'
    },*/
    {   name: 'WordNet 3.0',
        url: 'http://wordnetweb.princeton.edu/perl/webwn?s=*',
        scrollY: 170
    },
    {   name: 'Webster 1913 (OneLook)',
        url: 'http://www.onelook.com/?other=web1913&w=*',
        scrollY: 200
    },
    {   name: 'Webster 1913 (Extended)',
        url: 'http://www.webster-dictionary.org/definition/*',
        target: 'TitleLine'
    },
    {   name: 'The Free Dictionary (Print)',
        url: 'http://www.tfd.com/p/*',
        target: 'MainTxt'
    },
    {   name: 'InfoPlease Dictionary',
        url: 'http://dictionary.infoplease.com/*',
        target: 'meaning'
    },
    {   name: 'RhymeZone',
        url: 'http://www.rhymezone.com/r/rhyme.cgi?Word=*',
        scrollX: 30,
        scrollY: 310
    },
    {   name: 'WordSmyth',
        url: 'http://www.wordsmyth.net/live/home.php?script=search&matchent=*&matchtype=exact',
        scrollY: 210
    },
    {   name: 'Wiktionary',
        url: 'http://en.wiktionary.org/wiki/*',
        target: 'firstHeading'
    },
    {   name: 'Answers.com',
        url: 'http://www.answers.com/topic/*',
        scrollX: 178,
        scrollY: 283
    },
    {   name: 'The Free Dictionary',
        url: 'http://www.tfd.com/*',
        target: 'MainTitle'
    },
    {   name: 'Dictionary.com',
        url: 'http://dictionary.reference.com/browse/*',
        target: 'query_h1'
    },
    {   name: 'Merriam-Webster',
        url: 'http://www.merriam-webster.com/dictionary/*',
        target: 'mwEntryData',
        scrollX: -5
    },
    {   name: 'YourDictionary.com',
        url: 'http://www.yourdictionary.com/*',
        target: 'def'
    },
    {   name: 'AllWords.com',
        url: 'http://www.allwords.com/word-*.html',
        scrollX: 175,
        scrollY: 138
    },
    {   name: 'Google',
        url: 'http://www.google.com/search?q=*',
        target: 'res'
    },
    {   name: 'Yahoo',
        url: 'http://www.yahoo.com/search?q=*',
        target: 'main'
    },
    {   name: 'Bing',
        url: 'http://www.bing.com/search?q=*',
        target: 'results'
    },
    {   name: 'Wikipedia',
        url: 'http://en.wikipedia.org/wiki/*',
        target: 'firstHeading',
        scrollX: 240,
        scrollY: 10
    },
    {   name: 'Encyclopedia Britannica',
        url: 'http://www.britannica.com/bps/search?query=*',
        target: 'bps-checked-did-you-mean'
    },
    {   name: 'InfoPlease Encyclopedia',
        url: 'http://www.infoplease.com/search?q=*&in=all',
        target: 'SearchList'
    },
    {   name: 'Encyclopedia.com',
        url: 'http://www.encyclopedia.com/topic/*.aspx',
        target: 'docpart'
    }
];
var includes = DEFAULT_SOURCES.map(function(src){
    return src.url.substr(0, src.url.indexOf("*"));
});
function matchSrcIndex(url){
    for (var i=0; i < includes.length; i++){
        if(url.substr(0, includes[i].length) == includes[i])
            return i;
    }
    return -1;
}